from fastapi import Depends, HTTPException, status
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
from sqlalchemy.orm import Session
from app.core.database import get_db
from app.core.security import verify_token
from app.crud.user import get_user_by_username
from app.models.user import User, UserRole

# HTTP Bearer安全模式
security = HTTPBearer()

# 获取当前用户
def get_current_user(
    credentials: HTTPAuthorizationCredentials = Depends(security),
    db: Session = Depends(get_db)
) -> User:
    # 获取令牌
    token = credentials.credentials
    # 验证令牌
    username = verify_token(token)
    if username is None:
        # 令牌无效
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="无法验证凭据",
            headers={"WWW-Authenticate": "Bearer"},
        )
    # 获取用户
    user = get_user_by_username(db, username=username)
    if user is None:
        # 用户不存在
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="无法验证凭据",
            headers={"WWW-Authenticate": "Bearer"},
        )
    # 返回用户
    return user

# 获取当前活跃用户
def get_current_active_user(current_user: User = Depends(get_current_user)):
    # 检查用户是否活跃
    if not current_user.is_active:
        # 用户不活跃
        raise HTTPException(status_code=400, detail="用户未激活")
    # 返回活跃用户
    return current_user

# 获取当前管理员用户
def get_current_admin_user(current_user: User = Depends(get_current_active_user)) -> User:
    """检查当前用户是否为管理员"""
    if current_user.role != UserRole.ADMIN:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="权限不足，需要管理员权限"
        )
    return current_user